// permission 查询,  权限分配， 菜单
const { Op, QueryTypes } = require('sequelize')
const { sequelize, AclRolePermission, AclPermission } = require('../models')
const Page = require('../modules/page')

function buildSqlStatement(sql, fileds) {
  if (typeof sql === 'string') {
    return sql.replace(':attr', fileds.join(','))
  }
  return sql.join(' ').replace(':attr', fileds.join(','))
}

/**
 * 权限列表管理
 *
 * @param {Object} roleIds, 角色IDs
 * @param {Page} page
 */
module.exports.list = async function (roleIds = [], page = new Page()) {
  const _options = {
    replacements: {},
    type: QueryTypes.SELECT,
  }

  const sql = ['SELECT :attr FROM `acl_permission` as `ap` WHERE `delete_time` IS NULL']
  if (roleIds.lenght) {
    sql.push(
      'AND `id` IN(SELECT `arp`.`permission_id` FROM `acl_role_permission` as `arp` WHERE `arp`.`role_id` IN(:roles))'
    )
    Object.assign(_options.replacements, { roles: roleIds })
  }

  let fileds = ['COUNT(`ap`.`id`) as `count`']
  const { count } = await sequelize.query(buildSqlStatement(sql, fileds), {
    ..._options,
    plain: true,
  })

  if (page.size > 0) {
    sql.push('LIMIT :offset,:limit')
    Object.assign(_options.replacements, {
      limit: page.size,
      offset: (page.number - 1) * page.size,
    })
  }

  fileds = [
    '`ap`.`id`',
    '`ap`.`parent_id`',
    '`ap`.`name`',
    '`ap`.`type`',
    '`ap`.`url`',
    '`ap`.`perms`',
    '`ap`.`component`',
    '`ap`.`order_num`',
  ]
  const rows = await sequelize.query(buildSqlStatement(sql, fileds), _options)

  return {
    total: count,
    pagenum: page.number,
    list: rows,
  }
}

/**
 * 根据角色获取菜单和权限列表
 * @param {Array} roles
 */
module.exports.menus = async function (roleIds) {
  const _options = {
    replacements: { roles: roleIds },
    type: QueryTypes.SELECT,
  }
  const sql = [
    'SELECT :attr FROM `acl_permission` AS `ap`  WHERE `ap`.`delete_time` IS NULL',
    'AND `id` IN(SELECT `arp`.`permission_id` FROM `acl_role_permission` as `arp` WHERE `arp`.`role_id` IN(:roles))',
  ]

  fileds = [
    '`ap`.`id`',
    '`ap`.`parent_id`',
    '`ap`.`name`',
    '`ap`.`type`',
    '`ap`.`perms`',
    '`ap`.`component`',
    '`ap`.`component_name`',
    '`ap`.`redirect`',
    '`ap`.`route`',
    '`ap`.`is_route`',
    '`ap`.`keep_alive`',
    '`ap`.`open_target`',
    '`ap`.`hidden`',
    '`ap`.`order_num`',
  ]
  const rows = await sequelize.query(buildSqlStatement(sql, fileds), _options)
  return rows
}

module.exports.rolePerms = async function () {
  const rolePerms = await AclRolePermission.findAll({
    include: {
      model: AclPermission,
      as: 'perm',
      attributes: ['url', 'perms'],
    },
  })

  return rolePerms.map((item) => {
    return item.toJSON()
  })
}
